import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { catchError, Observable, of, tap } from 'rxjs';
import { Hero } from './hero';
import { MessageService } from './message.service';
import { HEROES } from './mock-heroes';

@Injectable({
  providedIn: 'root'
})
export class HeroService {
  private heroesUrl = 'api/heroes';
  private log(message: string) {
    this.messageService.add(`HeroService:${message}`);
  }

  private handleError<T>(operation='operation', result?:T) {
    return (error:any): Observable<T> =>{
      console.log(error);
      this.log(`${operation} failed:${error.message}`);
      return of(result as T);
    }
  }

  constructor(private http: HttpClient,private messageService: MessageService) { }

  getHeroes(): Observable<Hero[]> {
    return this.http.get<Hero[]>(this.heroesUrl).pipe(
      tap(_ => this.log('feteched heroes')),
      catchError(this.handleError<Hero[]>('getHeroes', []))
    );    
  }

  getHero(id: number): Observable<Hero> {
    const url = `${this.heroesUrl}/${id}`;
    return this.http.get<Hero>(url).pipe(
      tap(_=>this.log(`fetched hero id=${id}`)),
      catchError(this.handleError<Hero>(`getHero id=${id}`))
    );
  }
}
